import Loading from "./Loading.js";

export default class Http {
	constructor() {}

	static get(url, callback) {
		let xhr;
		
		if (window.XMLHttpRequest) {
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xhr=new XMLHttpRequest();
		} else {
			// code for IE6, IE5
			xhr=new ActiveXObject("Microsoft.XMLHTTP");
		}

		xhr.open("GET",url,true);
		xhr.onreadystatechange = function() {
			if (xhr.readyState==4 && xhr.status==200) {
		    	callback(JSON.parse(xhr.responseText));
		    }
		}
		xhr.dataType = "json";
		xhr.withCredentials = "true";
		xhr.send();
	}

	static post(url, params, callback) {
		console.log(url)
//		Loading.show();	

		let formData = new FormData();
		for (let i in params) {
			formData.append(i, params[i]);
		}

		let xhr;
		if (window.XMLHttpRequest) {
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xhr = new XMLHttpRequest();
		} else {
			// code for IE6, IE5
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}

		xhr.open("POST", url, true);
		xhr.onreadystatechange = function() {
			if (xhr.readyState === 4 && xhr.status === 200) {
				Loading.hide();

				let data = {};
		    	try {
					data = JSON.parse(xhr.responseText);
		    	} catch (e) {
		    		console.log(e);
		    	}
				
				if (data.errno === 0) {
					callback(data);
				} else {
					alert("Server: " + data.errmsg);
				}
		    } else if (xhr.readyState === 4 && xhr.status === 500) {
				Loading.hide();
		    	alert("Server error: 500");
		    }
		}
		xhr.dataType = "json";
		xhr.withCredentials = "true";
		xhr.send(formData);
	}
}
